﻿/*******************************************************************************
 * Copyright © 2016 DJY 版权所有
 * Author: DJY
 * Description: 后台管理系统
 * Website：http://www.djyweb.cn
*********************************************************************************/

//#undef DEBUG

using Autofac;
using System;
using System.Threading;

namespace DJY.Code
{
    public class OperatorProvider
    {
        #region 服务注册
        static readonly ContainerBuilder containerBuilder = new ContainerBuilder();
        static readonly ReaderWriterLock readerWriterLock = new ReaderWriterLock();
        static IContainer serviceContainer = null;

        /// <summary>
        /// 注册服务
        /// </summary>
        /// <param name="register">注册器</param>
        public static void RegisteService(Action<ContainerBuilder> register)
        {
            if (register == null) return;
            register(containerBuilder);
            readerWriterLock.AcquireWriterLock(0);
            serviceContainer = containerBuilder.Build();
            readerWriterLock.ReleaseWriterLock();
        }

        /// <summary>
        /// 开始新的作用域
        /// </summary>
        /// <param name="tag">The tag applied to the Autofac.ILifetimeScope.</param>
        /// <returns></returns>
        public static ILifetimeScope BeginLifetimeScope(object tag)
        {
            readerWriterLock.AcquireReaderLock(0);

            try
            {
                if (serviceContainer == null)
                {
                    throw new ArgumentNullException("serviceContainer");
                }

                return tag == null ? serviceContainer.BeginLifetimeScope() : serviceContainer.BeginLifetimeScope(tag);
            }
            finally
            {
                readerWriterLock.ReleaseReaderLock();
            }
        }

        /// <summary>
        /// 解析服务
        /// </summary>
        /// <typeparam name="T">服务类型</typeparam>
        /// <returns></returns>
        public static T Resolve<T>()
        {
            readerWriterLock.AcquireReaderLock(0);
            try
            {
                if (serviceContainer == null || !serviceContainer.IsRegistered<T>()) return default(T);
                return serviceContainer.Resolve<T>();
            }
            catch
            {
                return default(T);
            }
            finally
            {
                readerWriterLock.ReleaseReaderLock();
            }
        }

        #region 缓存
        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <returns></returns>
        public static ICache GetCache()
        {
            return Resolve<ICache>();
        }

        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <param name="cacheKey">缓存键</param>
        /// <returns></returns>
        public static T GetCache<T>(string cacheKey)
        {
            ICache cache = Resolve<ICache>();
            return cache.GetCache<T>(cacheKey);
        }

        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <param name="cacheKey">缓存键</param>
        /// <param name="obj">对象</param>
        /// <returns></returns>
        public static void SetCache(string cacheKey,object obj)
        {
            ICache cache = Resolve<ICache>();
            if(CacheKeys.ExpireTimes.ContainsKey(cacheKey))
            {
                Tuple<TimeSpan, TimeSpan> expireTime = CacheKeys.ExpireTimes[cacheKey];
                if(expireTime.Item1 != TimeSpan.Zero)
                {
                    cache.SetCache(cacheKey, obj, DateTime.Now.Add(expireTime.Item1));
                }
                else if(expireTime.Item2 != TimeSpan.Zero)
                {
                    cache.SetCache(cacheKey, obj, expireTime.Item2);
                }
                else
                {
                    cache.SetCache(cacheKey, obj);
                }
            }
            cache.SetCache(cacheKey, obj);
        }

        /// <summary>
        /// 移除缓存
        /// </summary>
        /// <param name="cacheKey">缓存键</param>
        /// <returns></returns>
        public static void RemoveCache(string cacheKey)
        {
            Resolve<ICache>().RemoveCache(cacheKey);

        }

        /// <summary>
        /// 清空缓存
        /// </summary>
        /// <returns></returns>
        public static void ClearCache()
        {
            Resolve<ICache>().RemoveCache();

        }
        #endregion
        #endregion

        #region 配置
        public static string LoginUserKey
        {
            get;
        }

        public static string LoginProvider
        {
            get;
        }

        static OperatorProvider()
        {
            LoginUserKey = ConfigHelper.GetValue("LoginUserKey", "sys_loginuser");
            LoginProvider = ConfigHelper.GetValue("LoginProvider");
        }
        #endregion

        /// <summary>
        /// 获取当前登陆用户
        /// </summary>
        /// <returns></returns>
        public static OperatorModel GetCurrent()
        {
            string user = null;
            if (LoginProvider == "Cookie")
            {
                user = WebHelper.GetCookie(LoginUserKey);
            }
            else
            {
                user = WebHelper.GetSession(LoginUserKey);
            }

            OperatorModel model = null;
            if (string.IsNullOrEmpty(user))
            {
                model = new OperatorModel();
            }
            else
            {
                try
                {
                    model = DESEncrypt.Decrypt(user).ToObject<OperatorModel>();
                }
                catch
                {
                    model = new OperatorModel();
                }
            }

            return model;
        }

        public static void AddCurrent(OperatorModel operatorModel)
        {
            if (LoginProvider == "Cookie")
            {
                WebHelper.WriteCookie(LoginUserKey, DESEncrypt.Encrypt(operatorModel.ToJson()), 7200);
            }
            else
            {
                WebHelper.WriteSession(LoginUserKey, DESEncrypt.Encrypt(operatorModel.ToJson()));
            }

        }

        public static void RemoveCurrent()
        {
            if (LoginProvider == "Cookie")
            {
                WebHelper.RemoveCookie(LoginUserKey);
            }
            else
            {
                WebHelper.RemoveSession(LoginUserKey);
            }
        }
    }
}
